<?php

/**
 * 用户注册，登录函数
 *
 * @access  public
 * @param   string       $username          注册用户名
 * @param   string       $password          用户密码
 * @param   string       $email             注册email
 * @param   array        $other             注册的其他信息
 *
 * @return  bool         $bool
 */
function register($username, $password, $email, $other = array()){
	$CommonModel			=	new CommonModel();
	$result					=	array();
	
    /*检查注册是否关闭
    if (!empty($GLOBALS['_CFG']['shop_reg_closed'])){
        $result['error']	=	$GLOBALS['_LANG']['shop_register_closed'];
    }
    */ 	
    //检查username
    if (empty($username)){
        $result['error']	=	$GLOBALS['_LANG']['username_empty'];
    }
    else{
        if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username)){
            $result['error']=	sprintf($GLOBALS['_LANG']['username_invalid'], htmlspecialchars($username));
        }
    }

    //检查email 
    if (empty($email)){
        $result['error']	=	$GLOBALS['_LANG']['email_empty'];
    }
    else{
        if (!is_email($email)){
            $result['error']	=	sprintf($GLOBALS['_LANG']['email_invalid'], htmlspecialchars($email));
        }
    }

    /*检查是否和管理员重名*/
    if(admin_registered($username)){
        $result['error']		=	sprintf($GLOBALS['_LANG']['username_exist'], $username);
        return false;
    } 
	 
    // 加载商城用户处理插件
    //UC
    /*Vendor('Integrates.ucenter');    
    $User				=	new Ucenter();*/
    //QS
    Vendor('Integrates.ecshop');
    $User				=	new Ecshop();
    $GLOBALS['ecs']		=	& $User;    
    
    if (!$User->add_user($username, $password, $email)){
        if ($User->error == ERR_INVALID_USERNAME){ 
            $result['error']		=	sprintf(sprintf($GLOBALS['_LANG']['username_invalid'], $username));       
        }
        elseif ($User->error == ERR_USERNAME_NOT_ALLOW){
            $result['error']		=	sprintf($GLOBALS['_LANG']['username_not_allow'], $username);
        }
        elseif ($User->error == ERR_USERNAME_EXISTS){
            $result['error']		=	sprintf($GLOBALS['_LANG']['username_exist'], $username);
        }
        elseif ($User->error == ERR_INVALID_EMAIL){
            $result['error']		=	sprintf($GLOBALS['_LANG']['email_invalid'], $email);
        }
        elseif ($User->error == ERR_EMAIL_NOT_ALLOW){
            $result['error']		=	sprintf($GLOBALS['_LANG']['email_not_allow'], $email);
        }
        elseif ($User->error == ERR_EMAIL_EXISTS){
            $result['error']		=	sprintf($GLOBALS['_LANG']['email_exist'], $email);
        }
        else{
            $result['error']		=	'UNKNOWN ERROR!';
        }        
        $GLOBALS['error']			=	$result['error'];        
        //注册失败
        return false;
    }
    else{
        //注册成功
        /* 设置成登录状态 */
        $User->set_session($username);
        $User->set_cookie($username);    	
    	
        /* 注册送积分 */
        if (!empty($GLOBALS['_CFG']['register_points'])){
            log_account_change($_SESSION['user_id'], 0, 0, $GLOBALS['_CFG']['register_points'], $GLOBALS['_CFG']['register_points'], $GLOBALS['_LANG']['register_points']);
        }
		
        /*推荐处理*/
        $affiliate  			=	unserialize($GLOBALS['_CFG']['affiliate']);
        if (isset($affiliate['on']) && $affiliate['on'] == 1){
            // 推荐开关开启
            $up_uid     		= 	get_affiliate();
            empty($affiliate) && $affiliate = array();
            $affiliate['config']['level_register_all'] = intval($affiliate['config']['level_register_all']);
            $affiliate['config']['level_register_up'] = intval($affiliate['config']['level_register_up']);
            if ($up_uid){
                if (!empty($affiliate['config']['level_register_all'])){
                    if (!empty($affiliate['config']['level_register_up'])){
                        $rank_points 	= 	$CommonModel->getOne("SELECT rank_points FROM " . ' ybr_users ' . " WHERE user_id = '$up_uid'");
                        if ($rank_points + $affiliate['config']['level_register_all'] <= $affiliate['config']['level_register_up']){
                            log_account_change($up_uid, 0, 0, $affiliate['config']['level_register_all'], 0, sprintf($GLOBALS['_LANG']['register_affiliate'], $_SESSION['user_id'], $username));
                        }
                    }
                    else{
                        log_account_change($up_uid, 0, 0, $affiliate['config']['level_register_all'], 0, $GLOBALS['_LANG']['register_affiliate']);
                    }
                }
                //设置推荐人
                $sql 			= 	'UPDATE '. ' ybr_users ' . ' SET parent_id = ' . $up_uid . ' WHERE user_id = ' . $_SESSION['user_id'];
                $CommonModel->query($sql);
            }
        }

        //定义other合法的变量数组
        $other_key_array 			= 	array('msn', 'qq', 'office_phone', 'home_phone', 'mobile_phone');
        $update_data['reg_time'] 	= 	local_strtotime(local_date('Y-m-d H:i:s'));
        if ($other){
            foreach ($other as $key=>$val){
                //删除非法key值
                if (!in_array($key, $other_key_array)){
                    unset($other[$key]);
                }
                else{
                    $other[$key] 	=  	htmlspecialchars(trim($val)); //防止用户输入javascript代码
                }
            }
            $update_data 			= 	array_merge($update_data, $other);
        }
        $CommonModel->autoExecute('users', $update_data, 'UPDATE', 'user_id = ' . $_SESSION['user_id']);
        update_user_info();      // 更新用户信息
        recalculate_price();     // 重新计算购物车中的商品价格
        return true;
    }
}

/**
 * 判断超级管理员用户名是否存在
 * @param   string      $adminname 超级管理员用户名
 * @return  boolean
 */
function admin_registered( $adminname ){	
	$CommonModel	=	new CommonModel();	
    $res 			= 	$CommonModel->getOne("SELECT COUNT(*) FROM " . ' ybr_admin_user ' . " WHERE user_name = '$adminname'");
    return $res;
}


/**
 * 获取推荐uid
 *
 * @access  public
 * @param   void
 *
 * @return int
 * @author xuanyan
 **/
function get_affiliate(){
	
	$CommonModel		=	new CommonModel();
	
    if (!empty($_COOKIE['ecshop_affiliate_uid'])){
        $uid 			= 	intval($_COOKIE['ecshop_affiliate_uid']);
        if ($CommonModel->getOne('SELECT user_id FROM ' . 'ybr_users' . "WHERE user_id = '$uid'")){
            return $uid;
        }
        else{
            setcookie('ecshop_affiliate_uid', '', 1);
        }
    }
    return 0;
}


/**
 * 禁止当前页面本缓存,多用于用户登陆
 * Enter description here ...
 */
function forbid_cache(){
	@header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");//标记内容最后修改时间
	@header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");//内容过期时间 
	@header("Cache-Control: no-cache, must-revalidate" );//强制不缓存
	@header("Pragma: no-cache" );//禁止本页被缓存	
}

/**
 * 设置登陆用户的权限
 * @param	$username	string
 * @return	2:用户名为空;
 * 			3:不存在该用户,需要跳转到激活页面进行二次注册
 * 
 */
function set_user_auth($username = null){
	$msg	=	array();
	if(empty($username)){
		$msg['error']	=	2;
		return $msg;
	}	
	
    $map['user_name']	= 	$username;			
	$authInfo 			= 	RBAC::authenticate($map);
	if(false === $authInfo) {				
		$msg['error']	=	3;		
	}else{
		RBAC::saveAccessList($authInfo['user_id']);							
		//session记录登陆的用户信息
		$_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
		$_SESSION['name']         		=  	$authInfo['user_name'];
		$_SESSION['user_name']    		=   $authInfo['user_name'];	//兼容前台用户
		$_SESSION['id']          	 	=   $authInfo['user_id'];
		$_SESSION['user_id']      		=   $authInfo['user_id'];	//兼容前台用户系统				
	}	
	return $msg;
}






























